<template>
  <el-dialog
    :model-value="visible"
    class="create-defect-dialog"
    width="1400px"
    align-center
    :close-on-click-modal="false"
    :show-close="false"
    :before-close="handleClose"
    @update:model-value="(value: boolean) => emit('update:visible', value)"
  >
    <template #header>
      <div class="dialog-header-wrapper">
        <div class="dialog-header-title">新建缺陷</div>
        <div class="dialog-header-actions">
          <el-button @click="handleClose">关闭</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            :disabled="!canCreate"
            @click="handleSubmit"
          >
            确认
          </el-button>
        </div>
      </div>
    </template>

    <div class="create-defect">
      <div class="detail-body">
        <div class="primary-column">
          <div class="detail-header">
            <div class="header-top">
              <div class="status-tags">
                <el-tag
                  v-if="formData.status"
                  :type="getStatusType(formData.status)"
                  size="small"
                >
                  {{ getStatusText(formData.status) }}
                </el-tag>
                <el-tag
                  v-if="formData.priority"
                  :type="getPriorityType(formData.priority)"
                  size="small"
                >
                  {{ getPriorityText(formData.priority) }}
                </el-tag>
                <el-tag
                  v-if="formData.severity"
                  :type="getSeverityType(formData.severity)"
                  size="small"
                >
                  {{ getSeverityText(formData.severity) }}
                </el-tag>
                <el-tag v-if="formData.type" size="small" type="info">
                  {{ getTypeText(formData.type) }}
                </el-tag>
              </div>
            </div>

            <div class="title-section" ref="titleFieldRef">
              <div class="field-label">
                <span>缺陷标题</span>
                <span class="required">*</span>
              </div>
              <el-input
                v-model="formData.title"
                placeholder="请输入缺陷标题"
                maxlength="200"
                show-word-limit
                size="large"
                class="title-input"
                :class="{ 'field-error': fieldErrors.title }"
                @input="clearFieldError('title')"
              />
              <div v-if="fieldErrors.title" class="error-message">{{ fieldErrors.title }}</div>
            </div>
          </div>

          <section class="section-card description-section">
            <div class="section-header">
              <div class="section-title">缺陷描述</div>
              <div class="section-actions">
                <el-button-group size="small">
                  <el-button @click="insertTemplate('description')">插入缺陷描述</el-button>
                  <el-button @click="insertTemplate('reproduce')">插入复现步骤</el-button>
                  <el-button @click="insertTemplate('expected')">插入期望结果</el-button>
                  <el-button @click="insertTemplate('actual')">插入实际结果</el-button>
                </el-button-group>
              </div>
            </div>
            <div class="description-content">
              <EnhancedRichTextEditor
                ref="descriptionEditorRef"
                v-model="formData.description"
                placeholder="请描述缺陷内容，可使用上方按钮插入格式化模块..."
                :min-height="400"
              />
            </div>
          </section>

          <!-- 关联区域 -->
          <section class="section-card association-section">
            <div class="section-header">
              <div class="section-title">关联</div>
            </div>
            <el-tabs v-model="associationSubTab" type="border-card" class="association-sub-tabs">
              <!-- 关联需求子页签 -->
              <el-tab-pane label="关联需求" name="requirements">
                <div class="sub-tab-content">
                  <div class="tab-header">
                    <div class="header-info">
                      <span class="item-count">已选择需求（{{ selectedRequirements.length }}）</span>
                    </div>
                    <div class="header-actions">
                      <el-button
                        type="primary"
                        size="small"
                        @click="showSelectRequirementDialog = true"
                      >
                        <el-icon><Plus /></el-icon>
                        添加需求
                      </el-button>
                    </div>
                  </div>

                  <div class="items-list">
                    <template v-if="selectedRequirements.length > 0">
                      <el-table
                        :data="selectedRequirements"
                        size="default"
                        border
                        stripe
                        style="width: 100%"
                        key="requirements-table"
                      >
                        <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip />
                        <el-table-column prop="status" label="状态" width="100">
                          <template #default="{ row }">
                            <el-tag :type="getRequirementStatusType(row.status) as any" size="small">
                              {{ getRequirementStatusName(row.status) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="priority" label="优先级" width="90">
                          <template #default="{ row }">
                            <el-tag :type="getRequirementPriorityType(row.priority) as any" size="small">
                              {{ getRequirementPriorityName(row.priority) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="project_name" label="所属项目" width="120" show-overflow-tooltip />
                        <el-table-column label="操作" width="120" fixed="right">
                          <template #default="{ row }">
                            <el-button
                              link
                              type="danger"
                              size="small"
                              @click="handleRemoveRequirement(row.id)"
                            >
                              移除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                    <el-empty v-else description="暂无关联需求，点击添加需求进行关联" :image-size="80" />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </section>
        </div>

        <aside class="side-column">
          <section class="info-card">
            <div class="info-card-title">基础字段</div>
            <div class="info-form-group" ref="statusFieldRef">
              <label class="info-label">状态</label>
              <el-select
                v-model="formData.status"
                placeholder="请选择状态"
                size="default"
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group" ref="priorityFieldRef">
              <label class="info-label">优先级 <span class="required">*</span></label>
              <el-select
                v-model="formData.priority"
                placeholder="请选择优先级"
                size="default"
                :class="{ 'field-error': fieldErrors.priority }"
                @change="clearFieldError('priority')"
              >
                <el-option
                  v-for="option in priorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <div v-if="fieldErrors.priority" class="error-message">{{ fieldErrors.priority }}</div>
            </div>
            <div class="info-form-group" ref="severityFieldRef">
              <label class="info-label">严重程度 <span class="required">*</span></label>
              <el-select
                v-model="formData.severity"
                placeholder="请选择严重程度"
                size="default"
                :class="{ 'field-error': fieldErrors.severity }"
                @change="clearFieldError('severity')"
              >
                <el-option
                  v-for="option in severityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <div v-if="fieldErrors.severity" class="error-message">{{ fieldErrors.severity }}</div>
            </div>
            <div class="info-form-group" ref="typeFieldRef">
              <label class="info-label">缺陷类型 <span class="required">*</span></label>
              <el-select
                v-model="formData.type"
                placeholder="请选择缺陷类型"
                size="default"
                :class="{ 'field-error': fieldErrors.type }"
                @change="clearFieldError('type')"
              >
                <el-option
                  v-for="option in typeOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
              <div v-if="fieldErrors.type" class="error-message">{{ fieldErrors.type }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">缺陷来源</label>
              <el-select
                v-model="formData.source"
                placeholder="请选择来源"
                size="default"
              >
                <el-option
                  v-for="option in sourceOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group" ref="projectIdFieldRef">
              <label class="info-label">所属项目 <span class="required">*</span></label>
              <el-select
                v-model="formData.project_id"
                placeholder="请选择项目"
                filterable
                size="default"
                :class="{ 'field-error': fieldErrors.project_id }"
                @change="handleProjectChange"
              >
                <el-option
                  v-for="project in projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
              <div v-if="fieldErrors.project_id" class="error-message">{{ fieldErrors.project_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">关联版本</label>
              <el-select
                v-model="formData.version"
                placeholder="请选择版本"
                filterable
                size="default"
              >
                <el-option
                  v-for="version in availableVersionOptions"
                  :key="version.id"
                  :label="version.name"
                  :value="version.id"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">缺陷标签</label>
              <el-select
                v-model="formData.tags"
                multiple
                filterable
                allow-create
                default-first-option
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择标签或输入新标签"
                size="default"
              >
                <el-option
                  v-for="tag in commonTagOptions"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">人员</div>
            <div class="info-form-group" ref="reporterIdFieldRef">
              <label class="info-label">报告人 <span class="required">*</span></label>
              <el-select
                v-model="formData.reporter_id"
                placeholder="请选择报告人"
                filterable
                clearable
                size="default"
                :class="{ 'field-error': fieldErrors.reporter_id }"
                @change="clearFieldError('reporter_id')"
              >
                <template #prefix>
                  <UserAvatar
                    v-if="formData.reporter_id"
                    :user="getUserById(formData.reporter_id)"
                    size="small"
                    circle
                    class="select-prefix-avatar"
                  />
                </template>
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <div class="user-option">
                    <UserAvatar
                      :user="user"
                      size="small"
                      circle
                    />
                    <span>{{ user.name }}</span>
                  </div>
                </el-option>
              </el-select>
              <div v-if="fieldErrors.reporter_id" class="error-message">{{ fieldErrors.reporter_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">负责人</label>
              <el-select
                v-model="formData.assignee_id"
                placeholder="请选择负责人（可选）"
                filterable
                clearable
                size="default"
              >
                <template #prefix>
                  <UserAvatar
                    v-if="formData.assignee_id"
                    :user="getUserById(formData.assignee_id)"
                    size="small"
                    circle
                    class="select-prefix-avatar"
                  />
                </template>
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <div class="user-option">
                    <UserAvatar
                      :user="user"
                      size="small"
                      circle
                    />
                    <span>{{ user.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">验证人</label>
              <el-select
                v-model="formData.verifier_id"
                placeholder="请选择验证人（可选）"
                filterable
                clearable
                size="default"
              >
                <template #prefix>
                  <UserAvatar
                    v-if="formData.verifier_id"
                    :user="getUserById(formData.verifier_id)"
                    size="small"
                    circle
                    class="select-prefix-avatar"
                  />
                </template>
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <div class="user-option">
                    <UserAvatar
                      :user="user"
                      size="small"
                      circle
                    />
                    <span>{{ user.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">时间信息</div>
            <div class="info-form-group">
              <label class="info-label">发现时间</label>
              <el-date-picker
                v-model="formData.found_date"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择发现时间"
                size="default"
                style="width: 100%"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">完成时间</label>
              <el-date-picker
                v-model="formData.completed_at"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择完成时间"
                size="default"
                style="width: 100%"
              />
              <div class="field-hint">设置完成时间后，系统将根据此时间统计逾期数据</div>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">环境信息</div>
            <div class="info-form-group">
              <label class="info-label">环境类型</label>
              <el-select
                v-model="environmentType"
                placeholder="请选择环境"
                size="default"
              >
                <el-option
                  v-for="option in environmentOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </div>
          </section>
        </aside>
      </div>
    </div>

    <!-- 需求选择对话框 -->
    <el-dialog
      v-model="showSelectRequirementDialog"
      width="700px"
      title="选择需求"
      @open="loadRequirements"
      @close="resetRequirementSelection"
    >
      <div class="select-requirement-dialog">
        <el-input
          v-model="requirementSearchQuery"
          placeholder="搜索需求标题或ID"
          clearable
          size="large"
          class="search-input"
        />

        <el-table
          v-loading="loadingRequirements"
          :data="filteredRequirements"
          @row-click="handleSelectRequirement"
          style="width: 100%"
        >
          <el-table-column prop="id" label="需求ID" width="100" />
          <el-table-column prop="title" label="需求标题" />
          <el-table-column prop="project_name" label="所属项目" />
          <el-table-column prop="priority" label="优先级" width="100" />
          <el-table-column prop="status" label="状态" width="100" />
        </el-table>

        <div class="dialog-footer">
          <el-button @click="showSelectRequirementDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectRequirement">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import EnhancedRichTextEditor from '@/components/common/EnhancedRichTextEditor.vue'
import UserAvatar from '@/components/ui/UserAvatar.vue'
import { defectAPI as defectApi } from '@/api/defect'
import { requirementAPI } from '@/api/requirements'
import { useDefectStates } from '@/composables/useDefectStates'
import { useDefectOptions } from '@/composables/useDefectOptions'
import type { Defect, DefectCreate, DefectStatus, DefectSource } from '@/api/defect'
import type { RequirementResponse } from '@/api/requirements'
import type { ProjectResponse } from '@/api/project'
import type { User } from '@/types/user'

// 扩展 DefectCreate 类型以支持 requirement_ids 和其他字段
interface ExtendedDefectCreate extends DefectCreate {
  requirement_ids?: string[]
  version?: string
  reproduce_steps?: string
  resolved_date?: string
  verified_date?: string
}

// Props
const props = defineProps<{
  visible: boolean
  currentUserId?: string
  defaultProjectId?: string
  defaultStatus?: string
  projects: ProjectResponse[]
  users: User[]
  typeOptions: Array<{ value: string; label: string }>
  severityOptions: Array<{ value: string; label: string }>
  priorityOptions: Array<{ value: string; label: string }>
  statusOptions?: Array<{ value: string; label: string }>
  versionOptions: Array<any>
  commonTags?: string[]
}>()

// Emits
const emit = defineEmits<{
  (event: 'update:visible', value: boolean): void
  (event: 'close'): void
  (event: 'created', defect: Defect): void
}>()

// 使用 composables 提供的函数（需要在 formData 之前声明）
const { getStatusName: getDefectStatusNameFromComposable, getStatusType: getDefectStatusTypeFromComposable } = useDefectStates()
const { formattedSourceOptions: defectSourceOptions, defaultSource } = useDefectOptions()

// 表单数据
const formData = reactive<ExtendedDefectCreate>({
  title: '',
  type: 'functional',
  severity: 'minor',
  priority: 'medium',
  source: (defaultSource.value?.code || 'testing') as DefectSource,
  description: '',
  reproduce_steps: '',
  expected_result: '',
  actual_result: '',
  project_id: props.defaultProjectId || '',
  version: '',
  reporter_id: props.currentUserId || '',
  assignee_id: '',
  verifier_id: '',
  status: (props.defaultStatus || 'new') as DefectStatus,
  found_date: '',
  completed_at: '',
  requirement_ids: [],
  tags: []
})

// 字段错误信息
const fieldErrors = reactive<Record<string, string>>({})

// 字段引用
const titleFieldRef = ref<HTMLElement | null>(null)
const typeFieldRef = ref<HTMLElement | null>(null)
const severityFieldRef = ref<HTMLElement | null>(null)
const priorityFieldRef = ref<HTMLElement | null>(null)
const statusFieldRef = ref<HTMLElement | null>(null)
const projectIdFieldRef = ref<HTMLElement | null>(null)
const reporterIdFieldRef = ref<HTMLElement | null>(null)
const descriptionEditorRef = ref<any>(null)

// 标签页
const associationSubTab = ref('requirements')

// 环境信息 - 改为下拉选择
const environmentType = ref('')
const environmentOptions = [
  { value: 'development', label: '开发环境' },
  { value: 'testing', label: '测试环境' },
  { value: 'staging', label: '预发布环境' },
  { value: 'production', label: '生产环境' }
]

// 常用标签选项
const commonTagOptions = computed(() => {
  return props.commonTags || []
})

// 关联需求
const selectedRequirements = ref<RequirementResponse[]>([])
const showSelectRequirementDialog = ref(false)
const requirementSearchQuery = ref('')
const loadingRequirements = ref(false)
const allRequirements = ref<RequirementResponse[]>([])
const filteredRequirements = computed(() => {
  if (!requirementSearchQuery.value) return allRequirements.value
  return allRequirements.value.filter((item: RequirementResponse) => 
    item.title?.includes(requirementSearchQuery.value) || 
    item.id?.includes(requirementSearchQuery.value)
  )
})

// 正在提交
const submitting = ref(false)

// 计算属性 - 可用的版本选项
const availableVersionOptions = computed(() => {
  if (!formData.project_id) return []
  return props.versionOptions.filter(version => version.project_id === formData.project_id)
})

// 计算属性 - 是否可以创建
const canCreate = computed(() => {
  return Boolean(
    formData.title.trim() &&
    formData.type &&
    formData.severity &&
    formData.priority &&
    formData.project_id
  )
})

// 状态选项（如果没有传入，使用默认值）
const statusOptions = computed(() => {
  return props.statusOptions || [
    { value: 'new', label: '新建' },
    { value: 'open', label: '打开' },
    { value: 'in_progress', label: '进行中' },
    { value: 'resolved', label: '已解决' },
    { value: 'closed', label: '已关闭' }
  ]
})

// 缺陷来源选项
const sourceOptions = computed(() => {
  return defectSourceOptions.value.map((opt: any) => ({
    value: opt.value || opt.code,
    label: opt.label || opt.name
  }))
})


// 获取状态文本
const getStatusText = (status?: string) => {
  if (!status) return '未设置状态'
  return getDefectStatusNameFromComposable(status)
}

// 获取状态类型
const getStatusType = (status?: string) => {
  if (!status) return 'info'
  return getDefectStatusTypeFromComposable(status)
}

// 获取优先级文本
const getPriorityText = (priority?: string) => {
  if (!priority) return ''
  const option = props.priorityOptions.find(opt => opt.value === priority)
  return option?.label || priority
}

// 获取优先级类型
const getPriorityType = (priority?: string): 'info' | 'success' | 'warning' | 'danger' => {
  if (!priority) return 'info'
  const lower = priority.toLowerCase()
  if (lower === 'high' || lower === 'urgent' || lower === 'critical') return 'danger'
  if (lower === 'medium' || lower === 'normal') return 'warning'
  return 'info'
}

// 获取严重程度文本
const getSeverityText = (severity?: string) => {
  if (!severity) return ''
  const option = props.severityOptions.find(opt => opt.value === severity)
  return option?.label || severity
}

// 获取严重程度类型
const getSeverityType = (severity?: string): 'info' | 'success' | 'warning' | 'danger' => {
  if (!severity) return 'info'
  const lower = severity.toLowerCase()
  if (lower.includes('严重') || lower.includes('critical') || lower.includes('致命')) return 'danger'
  if (lower.includes('高') || lower.includes('high') || lower.includes('major')) return 'warning'
  return 'info'
}

// 获取类型文本
const getTypeText = (type?: string) => {
  if (!type) return ''
  const option = props.typeOptions.find(opt => opt.value === type)
  return option?.label || type
}

// 根据用户ID获取用户对象（用于头像显示）
const getUserById = (userId?: string | null): User | null => {
  if (!userId) return null
  return props.users.find(u => u.id === userId) || null
}

// 需求状态辅助函数
const getRequirementStatusType = (status?: string): 'info' | 'success' | 'warning' | 'danger' => {
  if (!status) return 'info'
  const lower = status.toLowerCase()
  if (lower.includes('完成') || lower.includes('done') || lower.includes('closed')) return 'success'
  if (lower.includes('进行') || lower.includes('progress')) return 'warning'
  return 'info'
}

const getRequirementStatusName = (status?: string): string => {
  if (!status) return ''
  // 这里可以根据实际需求状态映射返回中文名称
  return status
}

const getRequirementPriorityType = (priority?: string): 'info' | 'success' | 'warning' | 'danger' => {
  if (!priority) return 'info'
  const lower = priority.toLowerCase()
  if (lower === 'high' || lower === 'urgent' || lower === 'critical') return 'danger'
  if (lower === 'medium' || lower === 'normal') return 'warning'
  return 'info'
}

const getRequirementPriorityName = (priority?: string): string => {
  if (!priority) return ''
  const map: Record<string, string> = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'urgent': '紧急',
    'critical': '严重'
  }
  return map[priority.toLowerCase()] || priority
}

// 清除字段错误
const clearFieldError = (field: string) => {
  if (fieldErrors[field]) {
    delete fieldErrors[field]
  }
}

// 滚动到字段
const scrollToField = (fieldName: string) => {
  const fieldRefs: Record<string, any> = {
    title: titleFieldRef,
    type: typeFieldRef,
    severity: severityFieldRef,
    priority: priorityFieldRef,
    status: statusFieldRef,
    project_id: projectIdFieldRef,
    reporter_id: reporterIdFieldRef
  }
  
  const ref = fieldRefs[fieldName]
  if (ref?.value) {
    ref.value.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '',
    type: 'functional',
    severity: 'minor',
    priority: 'medium',
    source: 'testing',
    description: '',
    reproduce_steps: '',
    expected_result: '',
    actual_result: '',
    project_id: props.defaultProjectId || '',
    version: '',
    reporter_id: props.currentUserId || '',
    assignee_id: '',
    verifier_id: '',
    status: (props.defaultStatus || 'new') as DefectStatus,
    found_date: new Date().toISOString().slice(0, 10),
    completed_at: '',
    requirement_ids: [],
    tags: []
  })
  
  // 清除错误信息
  Object.keys(fieldErrors).forEach(key => delete fieldErrors[key])
  
  // 重置选择的需求
  selectedRequirements.value = []
  associationSubTab.value = 'requirements'
  
  // 重置环境信息
  environmentType.value = ''
  
  // 重置标签
  formData.tags = []
}

// 插入模板
const insertTemplate = (type: string) => {
  const templates: Record<string, string> = {
    description: '<h3>缺陷描述</h3><p>请详细描述缺陷的现象和影响...</p><br>',
    reproduce: '<h3>复现步骤</h3><ol><li>步骤1</li><li>步骤2</li><li>步骤3</li></ol><br>',
    expected: '<h3>期望结果</h3><p>描述期望的正确行为...</p><br>',
    actual: '<h3>实际结果</h3><p>描述实际发生的错误行为...</p><br>'
  }
  
  const template = templates[type] || ''
  if (template) {
    // 获取当前内容
    const currentContent = formData.description || ''
    // 插入模板
    formData.description = currentContent + template
    // 触发编辑器更新
    nextTick(() => {
      if (descriptionEditorRef.value && descriptionEditorRef.value.editor) {
        descriptionEditorRef.value.editor.focus()
      }
    })
  }
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
  setTimeout(() => {
    resetForm()
  }, 300)
}

// 验证表单
const validateForm = (): boolean => {
  // 清除之前的错误
  Object.keys(fieldErrors).forEach(key => delete fieldErrors[key])
  
  const errors: Record<string, string> = {} 
  
  // 验证必填字段
  if (!formData.title?.trim()) {
    errors.title = '请填写缺陷标题'
  }
  
  if (!formData.type) {
    errors.type = '请选择缺陷类型'
  }
  
  if (!formData.severity) {
    errors.severity = '请选择严重程度'
  }
  
  if (!formData.priority) {
    errors.priority = '请选择优先级'
  }
  
  if (!formData.project_id) {
    errors.project_id = '请选择所属项目'
  }
  
  // 更新错误信息
  Object.assign(fieldErrors, errors)
  
  // 如果有错误，定位到第一个错误字段
  if (Object.keys(errors).length > 0) {
    const firstErrorField = Object.keys(errors)[0]
    scrollToField(firstErrorField)
    ElMessage.warning('请完善必填字段')
    return false
  }
  
  return true
}

// 处理提交
const handleSubmit = async () => {
  if (!validateForm()) return
  
  submitting.value = true
  
  try {
    // 构建提交数据
    const submitData = { ...formData }
    
    // 处理 datetime 字段格式转换（将 "YYYY-MM-DD HH:mm:ss" 转换为 "YYYY-MM-DDTHH:mm:ss" ISO格式）
    // 注意：解决时间、验证时间、实际完成时间等字段不在新建表单中，由系统根据状态自动更新
    const datetimeFields = ['found_date', 'completed_at']
    datetimeFields.forEach(field => {
      const value = (submitData as any)[field]
      if (value && typeof value === 'string') {
        // 将 "YYYY-MM-DD HH:mm:ss" 格式转换为 "YYYY-MM-DDTHH:mm:ss" 格式（ISO格式）
        if (value.includes(' ')) {
          (submitData as any)[field] = value.replace(' ', 'T')
        } else if (!value.includes('T') && value.match(/^\d{4}-\d{2}-\d{2}$/)) {
          // 如果只有日期，添加时间部分（默认00:00:00）
          (submitData as any)[field] = `${value}T00:00:00`
        }
      } else if (value === '') {
        // 空字符串转为 undefined，不发送该字段
        (submitData as any)[field] = undefined
      }
    })
    
    // 确保不提交这些时间字段（它们应该由系统根据状态自动更新）
    delete (submitData as any).resolved_date
    delete (submitData as any).verified_date
    delete (submitData as any).completed_at
    delete (submitData as any).actual_completed_at
    
    // 构建环境信息对象（和详情页一致）
    if (environmentType.value) {
      submitData.environment_info = {
        additional_info: {
          environment: environmentType.value
        }
      } as any
    }
    
    // 添加关联需求
    submitData.requirement_ids = selectedRequirements.value.map((req: RequirementResponse) => req.id).filter(Boolean) as string[]
    
    // 调用API创建缺陷
    const response = await defectApi.createDefect(submitData)
    
    if (response.success && response.data) {
      ElMessage.success('缺陷创建成功')
      emit('created', response.data)
      resetForm()
      emit('update:visible', false)
    } else {
      ElMessage.error(response.message || '缺陷创建失败')
    }
  } catch (error: any) {
    console.error('创建缺陷失败:', error)
    const message = error.response?.data?.message || error.message || '创建缺陷失败，请稍后重试'
    ElMessage.error(message)
  } finally {
    submitting.value = false
  }
}

// 处理项目变更
const handleProjectChange = () => {
  // 当项目变更时，重置版本
  formData.version = ''
  clearFieldError('project_id')
}

// 加载需求列表
const loadRequirements = async () => {
  try {
    loadingRequirements.value = true
    const response = await requirementAPI.getRequirements({
      project_id: formData.project_id || undefined,
      page: 1,
      size: 100
    })
    allRequirements.value = response.items || []
  } catch (error) {
    console.error('加载需求列表失败:', error)
    ElMessage.error('加载需求列表失败，请稍后重试')
  } finally {
    loadingRequirements.value = false
  }
}

// 选择需求
const handleSelectRequirement = (row: RequirementResponse) => {
  // 检查是否已选中
  const existingIndex = selectedRequirements.value.findIndex((item: RequirementResponse) => item.id === row.id)
  if (existingIndex > -1) {
    selectedRequirements.value.splice(existingIndex, 1)
  } else {
    selectedRequirements.value.push(row)
  }
}

// 确认选择需求
const confirmSelectRequirement = () => {
  showSelectRequirementDialog.value = false
}

// 重置需求选择
const resetRequirementSelection = () => {
  requirementSearchQuery.value = ''
}

// 移除需求
const handleRemoveRequirement = (id: string) => {
  const index = selectedRequirements.value.findIndex((item: RequirementResponse) => item.id === id)
  if (index > -1) {
    selectedRequirements.value.splice(index, 1)
  }
}

// 监听可见性变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 对话框打开时的处理
    if (props.defaultProjectId) {
      formData.project_id = props.defaultProjectId
    }
    if (props.defaultStatus) {
      formData.status = props.defaultStatus as DefectStatus
    }
    if (props.currentUserId) {
      formData.reporter_id = props.currentUserId
    }
  } else {
    // 对话框关闭时，重置表单和标签页状态
    resetForm()
  }
}, { immediate: true })

// 监听项目变化
watch(() => props.defaultProjectId, (newVal) => {
  if (newVal && props.visible && !formData.project_id) {
    formData.project_id = newVal
  }
}, { immediate: true })

// 监听状态变化
watch(() => props.defaultStatus, (newVal) => {
  if (newVal && props.visible) {
    formData.status = newVal as DefectStatus
  }
}, { immediate: true })

// 监听当前用户变化
watch(() => props.currentUserId, (newVal) => {
  if (newVal && props.visible && !formData.reporter_id) {
    formData.reporter_id = newVal
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.create-defect-dialog {
  :deep(.el-dialog) {
    max-height: 90vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    padding: 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  :deep(.el-dialog__title) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 24px;
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}

.create-defect {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.detail-body {
  display: flex;
  gap: 24px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  align-items: flex-start;
}

.primary-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  padding-right: 8px;
  min-height: 0;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }
}

.detail-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.header-top {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.status-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.title-section {
  margin-bottom: 8px;
}

.title-input {
  width: 100%;
}

.section-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.description-section {
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid #ebeef5;
  }

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .section-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .description-content {
    padding: 24px;
  }
}

.side-column {
  width: 400px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 24px;
  position: sticky;
  top: 0;
  align-self: flex-start;
  gap: 16px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
}

.info-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 18px 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.info-card-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.info-form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  color: #909399;
  font-size: 13px;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
}

.field-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.field-error {
  :deep(.el-input__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }
  
  :deep(.el-select__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.5;
}

.field-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.dialog-header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 20px 24px;
  position: relative;
}

.dialog-header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.dialog-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

.association-sub-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-tabs__nav-wrap) {
    padding: 0;
  }

  :deep(.el-tabs__item) {
    padding: 12px 16px;
    font-size: 13px;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.sub-tab-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px 0;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;

  .header-info {
    .item-count {
      font-size: 13px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.items-list {
  min-height: 200px;
  max-height: 400px;
  overflow-y: auto;

  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table__header) {
    th {
      padding: 8px 0;
      font-size: 12px;
    }
  }

  :deep(.el-table__body) {
    td {
      padding: 8px 0;
      font-size: 12px;
    }
  }
}

.select-requirement-dialog {
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 400px;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
  
  span {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.select-prefix-avatar {
  margin-right: 8px;
  flex-shrink: 0;
}

:deep(.el-select__prefix) {
  display: flex;
  align-items: center;
}

.search-input {
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 992px) {
  .detail-body {
    flex-direction: column;
  }

  .side-column {
    width: 100%;
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding-left: 0;
    padding-top: 16px;
  }
}
</style>
